<template>
	<el-form :model="formData" ref="formRef" :rules="formRules" label-width="90px" label-position="left" style="margin-top: 12px!important;">
		<el-form-item label="科目代码：" prop="code">
            <el-input type="text" v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item label="科目名称：" prop="name">
            <el-input type="text" v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="助记码：" prop="mnemonicCode">
            <el-input type="text" v-model="formData.mnemonicCode"></el-input>
        </el-form-item>
        <el-form-item label="科目类别：" prop="type">
            <el-select v-model="formData.type" placeholder="选择科目类别" style="width: 100%">
                <el-option v-for="item in type" :label="item['name']" :value="String(item['id'])" :key="item['id']"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="余额方向：" prop="balanceDirection">
            <el-select v-model="formData.balanceDirection" placeholder="选择余额方向" style="width: 100%">
                <el-option label="借方" value="0"></el-option>
                <el-option label="贷方" value="1"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="外币核算：" prop="foreignCurrencyCheck">
            <el-select v-model="formData.foreignCurrencyCheck" placeholder="选择外币核算" style="width: 100%">
                <el-option label="不核算" value="0"></el-option>
                <el-option v-for="item in foreignCheck" :key="item['id']" :label="item['name']" :value="String(item['id'])"></el-option>
                <el-option label="所有币别" value="1002"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="出日记账：" prop="journal" style="margin-bottom: 0px !important">
            <el-checkbox v-model="formData.journal"></el-checkbox>
        </el-form-item>
        <el-form-item label="往来科目：" prop="betweenObject" style="margin-bottom: 0px !important">
            <el-checkbox v-model="formData.betweenObject"></el-checkbox>
        </el-form-item>
        <el-form-item label="连续新增：" v-if="!rowId">
            <el-checkbox v-model="continueAdd"></el-checkbox>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="small" @click="save('formRef')">保存</el-button>
            <el-button type="danger" size="small" @click="close">关闭</el-button>
        </el-form-item>
	</el-form>
</template>
<script>
export default {
	data() {
		return {
			formData: {},
			formRules: {
				code: [{required: true, message: '科目代码不能为空', triggle: 'blur'}],
                name: [{required: true, message: '科目名称不能为空', triggle: 'blur'}],
                type: [{required: true, message: '科目类别不能为空', triggle: 'change'}],
                balanceDirection: [{required: true, message: '余额方向不能为空', triggle: 'change'}],
                foreignCurrencyCheck: [{required: true, message: '外币核算不能为空', triggle: 'change'}]
			},
			type: [],				//科目类别
			foreignCheck: [],		//外币核算
			continueAdd: false,		//连续新增
            rowId: null
		}
	},
    watch: {
        'formData.betweenObject'(newVal) {      //监听往来科目是否被勾选
            this.$store.commit('accountSubjectStore/updateIsCheckBetweenObject', newVal);
        }
    },
	methods: {
        getUpdateData() {       //获取更新的会计科目数据
            this.$http.get('subjectGroup/selectGroupById?id=' + this.rowId).then(res => {
                if(res.data.code == 20001) {
                    if(res.data.data) {
                        let data = res.data.data;
                        this.formData = data;
                        this.formData['balanceDirection'] = this.formData['balanceDirection'].toString();
                        this.formData['foreignCurrencyCheck'] = this.formData['foreignCurrencyCheck'].toString();
                        this.formData['journal'] = Boolean(this.formData['journal']);
                        this.formData['betweenObject'] = Boolean(this.formData['betweenObject']);
                        this.$store.commit('accountSubjectStore/updateRowId');          //获取数据完成后，清空rowId,防止印象数据新增
                        if(data['typeName'] === '资产' || data['typeName'] === '负债' || data['typeName'] === '共同' || data['typeName'] === '权益' || data['typeName'] === '成本' || data['typeName'] === '损益' || data['typeName'] === '表外' || data['typeName'] === '会计科目') {
                            this.formData['type'] = '';
                        } else {
                            this.formData['type'] = data['type'].toString();
                        }
                        if(data['objectList'] && data['objectList'].length > 0) {
                            this.$store.commit('accountSubjectStore/updateBetweenObject', data['objectList']);     //更新往来对象数据
                        } else {
                            this.$store.commit('accountSubjectStore/clearBetweenObject');     //清空往来对象数据
                        }
                    }
                }
            });
        },
		getTypes() {		//获取科目类别
			this.$http.get('subjectGroup/selectAll').then(res => {
                if(res.data.code == 20001) {
                    if(res.data.data) {
                        this.type = res.data.data;
                    }
                }
            });
		},
		getForeignChecks() {     //获取外币核算
            this.$http.get('currency/findCurrency').then(res => {
                if(res.data.code == 20001) {
                    if(res.data.data) {
                        this.foreignCheck = res.data.data;
                    }
                }
            });
        },
		save(formName) {		//保存
			this.$refs[formName].validate((valid) => {
                if (valid) {
                    let data = {
                        code: this.formData['code'],            //科目代码
                        name: this.formData['name'],            //科目名称
                        mnemonicCode: this.formData['mnemonicCode'],        //助记码
                        type: Number(this.formData['type']),            //科目类别
                        balanceDirection: Number(this.formData['balanceDirection']),            //余额方向
                        foreignCurrencyCheck: Number(this.formData['foreignCurrencyCheck']),    //外币核算
                        journal: this.formData['journal'] ? 1 : 0,          //出日记账
                        betweenObject: this.formData['betweenObject'] ? 1 : 0       //往来科目复选框
                    }
                    //加上往来对象数据
                    let betweenObject = this.$store.state.accountSubjectStore.betweenObject;        //往来对象数据
                    if(betweenObject.length > 0) {
                        let newArr = [];
                        betweenObject.forEach(item => newArr.push(item['id']));
                        data['betweenObjectList'] = newArr.join(',');
                    } else {
                        data['betweenObjectList'] = '0';
                    }
                    //新增还是修改
                    if(this.formData['id']) {
                        //修改
                        data['id'] = this.formData['id'];
                        this.$http({
                            url: 'subjectGroup/insertOrUpdateBySubject',
                            method: 'post',
                            params: data
                        }).then(res => {
                            if(res.data.code == 20001) {
                                this.$message({type: 'success', message: '修改成功', duration: 1500});
                                setTimeout(() => {
                                    this.$store.dispatch('accountSubjectStore/getTreeData');        //刷新数据
                                    this.close();
                                }, 1000);
                            } else {
                                this.$message.error(res.data.msg || '修改失败');
                            }
                        });
                    } else {
                        //新增
                        if(betweenObject.length <= 0) {
                            this.$confirm('往来对象数据为空, 是否继续保存?', '保存提示', {
                              confirmButtonText: '确定',
                              cancelButtonText: '取消',
                              type: 'warning'
                            }).then(() => {
                                this.$http({
                                    url: 'subjectGroup/insertOrUpdateBySubject',
                                    method: 'post',
                                    params: data
                                }).then(res => {
                                    if(res.data.code == 20001) {
                                        this.$message({type: 'success', message: '新增成功', duration: 1500});
                                        setTimeout(() => {
                                            this.continueAdd ? this.$refs[formName].resetFields() : this.close();
                                            this.$store.dispatch('accountSubjectStore/getTreeData');        //刷新数据
                                        }, 1000);
                                    } else {
                                        this.$message.error(res.data.msg || '新增失败');
                                    }
                                }).catch(() => {
                                    this.$message({message: '已取消保存', type: 'info', duration: 1500});
                                });
                            }).catch(() => {})
                        } else {
                            this.$http({
                                url: 'subjectGroup/insertOrUpdateBySubject',
                                method: 'post',
                                params: data
                            }).then(res => {
                                if(res.data.code == 20001) {
                                    this.$message({type: 'success', message: '新增成功', duration: 1500});
                                    setTimeout(() => {
                                        this.$store.dispatch('accountSubjectStore/getTreeData');        //刷新数据
                                        this.close();
                                    }, 1000);
                                } else {
                                    this.$message.error(res.data.msg || '新增失败');
                                }
                            }).catch(() => {
                                this.$message({message: '已取消保存', type: 'info', duration: 1500});
                            });
                        }
                    }
                }
            });
		},
		close() {		//关闭弹窗
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
		}
	},
	created() {
        let rowId = this.$store.state.accountSubjectStore.rowId;
        this.rowId = rowId;
        if(rowId) {
            this.getUpdateData();
        }
		this.getTypes();
		this.getForeignChecks();
	}
}
</script>